<template>
  <div class="page-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <el-button type="primary" size="small" @click="openAddDialog">添加商品</el-button>
        </div>
      </template>
      <el-table
        :data="products"
        style="width: 100%"
        border
        class="product-table"
        stripe
        height="500px"
        :loading="loading"
      >
        <el-table-column prop="id" label="SPU ID" width="100" />
        <el-table-column prop="title" label="商品标题" min-width="180" />
        <el-table-column prop="categoryName" label="分类" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="toggleStatus(scope.row)"
              :disabled="scope.row.status === 3"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="fetchProducts"
        class="pagination"
      />
    </el-card>

    <el-dialog
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="商品标题" prop="title">
              <el-input v-model="productForm.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="productForm.categoryId" placeholder="请选择分类">
                <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="主图" prop="mainImage">
          <el-upload
            :action="uploadUrl"
            :on-success="handleImageUpload"
            :show-file-list="false"
            accept="image/*"
            class="image-uploader"
          >
            <el-image :src="productForm.mainImage || defaultImage" style="width: 100px; height: 100px;" />
            <template #tip>
              <div class="el-upload__tip">点击上传主图（JPG/PNG，最大 2MB）</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情" prop="detailHtml">
          <el-input v-model="productForm.detailHtml" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="SKU列表">
          <el-table :data="productForm.skus" border style="width: 100%">
            <el-table-column label="SKU图片" width="200">
              <template #default="scope">
                <el-image :src="scope.row.skuImage || defaultImage" style="width: 60px; height: 60px;" fit="cover" />
              </template>
            </el-table-column>
            <!-- <el-table-column label="规格">
              <template #default="scope">
                {{ formatSpecsForDisplay(scope.row.specs) }}
              </template>
            </el-table-column> -->
            <el-table-column prop="price" label="价格" width="120" />
            <el-table-column prop="stock" label="库存" width="100" />
            <el-table-column prop="warningStock" label="预警库存" width="100" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editSkuItem(scope.$index, scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="removeSku(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" size="small" @click="openSkuDialog('add')" style="margin-top: 12px;">添加SKU</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProduct">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog
      :title="skuDialogType === 'add' ? '添加SKU' : '编辑SKU'"
      v-model="skuDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="skuFormRef" :model="currentSku" :rules="skuRules" label-width="100px">
        <el-form-item label="SKU图片">
          <el-upload
            :action="uploadUrl"
            :on-success="handleCurrentSkuImageUpload"
            :show-file-list="false"
            accept="image/*"
            class="sku-image-uploader"
          >
            <el-image :src="currentSku.skuImage || defaultImage" style="width: 100px; height: 100px;" fit="cover" />
            <template #tip>
              <div class="el-upload__tip">点击上传SKU图片（JPG/PNG，最大 2MB）</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="规格" prop="specs">
          <div v-for="(spec, index) in currentSku.specs" :key="index" style="display: flex; margin-bottom: 10px; align-items: center;">
            <el-input v-model="spec.key" placeholder="例如：颜色" style="width: 45%; margin-right: 5px;"></el-input>
            <el-input v-model="spec.value" placeholder="例如：红色" style="width: 45%;"></el-input>
            <el-button
              type="danger"
              :icon="Delete"
              circle
              size="small"
              @click="removeCurrentSkuSpec(index)"
              style="margin-left: 5px;"
            ></el-button>
          </div>
          <el-button type="text" @click="addCurrentSkuSpec">添加规格项</el-button>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="currentSku.price" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="currentSku.stock" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="预警库存" prop="warningStock">
          <el-input-number v-model="currentSku.warningStock" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelSkuDialog">取消</el-button>
        <el-button type="primary" @click="submitSkuForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { getTaskCategory } from '@/api/product'
import { getProductsService, createProductService, updateProductService, toggleProductStatusService } from '@/api/merchant'
import defaultImage from '@/assets/default.png'
import { useUserInfoStore } from '@/stores/userInfo'
import { Delete } from '@element-plus/icons-vue' // Import the Delete icon

const userInfoStore = useUserInfoStore()
const products = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false) // Main product dialog
const dialogType = ref('add') // 'add' or 'edit' for product
const categories = ref([])
const baseUrl = 'http://localhost:8080'

const productForm = reactive({
  id: null,
  title: '',
  categoryId: null,
  mainImage: '',
  detailHtml: '',
  skus: [] // Array of SKU objects
})

const productRules = {
  title: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  mainImage: [{ required: true, message: '请上传主图', trigger: 'change' }]
}

const productFormRef = ref(null)
const uploadUrl = ref('/api/upload/avatar')

// --- SKU Dialog related state ---
const skuDialogVisible = ref(false) // SKU specific dialog visibility
const skuDialogType = ref('add') // 'add' or 'edit' for SKU
const currentSku = reactive({ // Temporary SKU object for the SKU dialog form
  id: null, // SKU ID, might exist for editing
  skuImage: '',
  specs: [{ key: '', value: '' }], // Array of spec { key, value } pairs
  price: 0,
  stock: 0,
  warningStock: 0
})
const currentSkuIndex = ref(null) // Index of the SKU being edited in the productForm.skus array

const skuFormRef = ref(null) // Ref for the SKU form validation

const skuRules = {
  specs: [{
    validator: (rule, value, callback) => {
      // Validate that at least one spec is present and has both key and value
      const hasValidSpec = value && value.some(s => s.key && s.value);
      if (!hasValidSpec) {
        callback(new Error('请至少添加一个有效的规格项'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  price: [{ required: true, type: 'number', min: 0, message: '请输入有效价格', trigger: 'blur' }],
  stock: [{ required: true, type: 'number', min: 0, message: '请输入有效库存', trigger: 'blur' }],
  warningStock: [{ required: true, type: 'number', min: 0, message: '请输入有效预警库存', trigger: 'blur' }]
}
// --- End SKU Dialog related state ---


const fetchProducts = async () => {
  try {
    const res = await getProductsService(
      userInfoStore.userInfo.id,
      currentPage.value,
      pageSize.value
    )
    console.log(res)
    products.value = res.data.data.records
    total.value = res.data.data.total || res.data.data.records.length
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

const fetchCategories = async () => {
  try {
    const res = await getTaskCategory()
    categories.value = res.data.data
    if (categories.value.length > 0 && !productForm.categoryId) {
      productForm.categoryId = categories.value[0].id
    }
  } catch (error) {
    ElMessage.error('获取分类失败')
  }
}

const openAddDialog = () => {
  dialogType.value = 'add'
  productForm.id = null
  productForm.title = ''
  productForm.categoryId = categories.value.length > 0 ? categories.value[0].id : null
  productForm.mainImage = ''
  productForm.detailHtml = ''
  productForm.skus = [] // Ensure skus are empty for a new product
  dialogVisible.value = true
}

const openEditDialog = (row) => {
  dialogType.value = 'edit'
  productForm.id = row.id
  productForm.title = row.title
  productForm.categoryId = row.categoryId
  productForm.mainImage = row.mainImage
  productForm.detailHtml = row.detailHtml
  // When editing, parse specsJson back into specs array for each SKU
  productForm.skus = row.skus.map(sku => {
    let parsedSpecs = [];
    try {
      parsedSpecs = sku.specsJson ? Object.entries(JSON.parse(sku.specsJson)).map(([key, value]) => ({ key, value })) : [];
    } catch (e) {
      console.error("Failed to parse specsJson for SKU ID:", sku.id, sku.specsJson, e);
      parsedSpecs = [];
    }
    return {
      ...sku,
      skuImage: sku.skuImage || '',
      specs: parsedSpecs // Use the new 'specs' array
    };
  }) || []
  dialogVisible.value = true
}

// Function to format specs for display in the main product table
const formatSpecsForDisplay = (specs) => {
  if (!specs || specs.length === 0) return '';
  return specs.map(spec => `${spec.key}: ${spec.value}`).join('; ');
}

// --- SKU Dialog functions ---
const openSkuDialog = (type, index = null, sku = null) => {
  skuDialogType.value = type;
  if (type === 'add') {
    // Reset currentSku for adding a new one
    Object.assign(currentSku, {
      id: null,
      skuImage: '',
      specs: [{ key: '', value: '' }],
      price: 0,
      stock: 0,
      warningStock: 0
    });
    currentSkuIndex.value = null; // No index for new SKU
  } else { // type === 'edit'
    // Deep copy the SKU to currentSku to avoid direct mutation
    Object.assign(currentSku, JSON.parse(JSON.stringify(sku)));
    currentSkuIndex.value = index;
  }
  skuDialogVisible.value = true;
  // Reset validation state for the SKU form
  if (skuFormRef.value) {
    skuFormRef.value.clearValidate();
  }
}

const editSkuItem = (index, sku) => {
  openSkuDialog('edit', index, sku);
}

const addCurrentSkuSpec = () => {
  currentSku.specs.push({ key: '', value: '' });
}

const removeCurrentSkuSpec = (index) => {
  currentSku.specs.splice(index, 1);
}

const handleCurrentSkuImageUpload = (response) => {
  if (response.url) {
    currentSku.skuImage = response.url.startsWith('http') ? response.url : `${baseUrl}${response.url}`
    ElMessage.success('SKU图片上传成功')
  } else {
    ElMessage.error('SKU图片上传失败')
  }
}

const submitSkuForm = async () => {
  if (!skuFormRef.value) return;

  try {
    const valid = await skuFormRef.value.validate();
    if (valid) {
      // Create a copy of currentSku to transform specs into specsJson
      const skuForSubmission = JSON.parse(JSON.stringify(currentSku));

      const specsObject = {};
      if (skuForSubmission.specs && Array.isArray(skuForSubmission.specs)) {
        skuForSubmission.specs.forEach(spec => {
          if (spec.key && spec.value) { // Only add if both key and value exist
            specsObject[spec.key] = spec.value;
          }
        });
      }
      skuForSubmission.specsJson = JSON.stringify(specsObject);
      delete skuForSubmission.specs; // Remove the temporary 'specs' array

      if (skuDialogType.value === 'add') {
        productForm.skus.push(skuForSubmission); // Add to the main product's skus array
      } else { // 'edit'
        // Replace the existing SKU at the specific index
        productForm.skus[currentSkuIndex.value] = skuForSubmission;
      }
      skuDialogVisible.value = false; // Close SKU dialog
      ElMessage.success(skuDialogType.value === 'add' ? 'SKU添加成功' : 'SKU更新成功');
    }
  } catch (error) {
    console.error('SKU表单验证失败:', error);
    ElMessage.error('SKU表单验证失败，请检查输入');
  }
}

const cancelSkuDialog = () => {
  skuDialogVisible.value = false;
}

// --- End SKU Dialog functions ---

const removeSku = (index) => {
  productForm.skus.splice(index, 1)
}

const handleImageUpload = (response) => {
  if (response.url) {
    productForm.mainImage = response.url.startsWith('http') ? response.url : `${baseUrl}${response.url}`
    ElMessage.success('主图上传成功')
  } else {
    ElMessage.error('主图上传失败')
  }
}

const formatStatus = (status) => {
  switch (status) {
    case 0: return '已下架'
    case 1: return '已上架'
    case 2: return '已下架'
    case 3: return '待审核'
    default: return '未知'
  }
}

const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'danger'
    case 1: return 'success'
    case 3: return 'warning'
    default: return ''
  }
}

const submitProduct = async () => {
  if (!productFormRef.value) {
    ElMessage.error('表单引用未找到')
    return
  }

  try {
    const valid = await productFormRef.value.validate()
    if (valid) {
      // Validate that there is at least one SKU
      if (productForm.skus.length === 0) {
        ElMessage.error('请至少添加一个SKU');
        return;
      }

      const productFormForSubmission = JSON.parse(JSON.stringify(productForm));

      // Ensure all SKUs have their specs converted to specsJson before submission
      productFormForSubmission.skus.forEach(sku => {
        // If sku.specs still exists (e.g., if somehow not processed by SKU dialog)
        // or if it's a new SKU that hasn't gone through the SKU dialog's submitSkuForm
        if (sku.specs && Array.isArray(sku.specs)) {
          const specsObject = {};
          sku.specs.forEach(spec => {
            if (spec.key && spec.value) {
              specsObject[spec.key] = spec.value;
            }
          });
          sku.specsJson = JSON.stringify(specsObject);
          delete sku.specs;
        } else if (!sku.specsJson) { // Handle cases where specsJson might be missing
             sku.specsJson = '{}';
        }
      });

      if (dialogType.value === 'add') {
        productFormForSubmission.merchantId = userInfoStore.userInfo.id
        await createProductService(productFormForSubmission)
        ElMessage.success('添加商品成功')
      } else {
        await updateProductService(productFormForSubmission)
        ElMessage.success('更新商品成功')
      }
      dialogVisible.value = false
      fetchProducts()
    }
  } catch (error) {
    console.error('商品表单提交失败:', error)
    ElMessage.error('商品表单提交失败，请检查输入')
  }
}

const toggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 2 : 1;
    await toggleProductStatusService(row.id, newStatus);
    ElMessage.success(newStatus === 2 ? '下架成功' : '上架成功');
    fetchProducts();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};


fetchProducts()
fetchCategories()
</script>

<style lang="scss" scoped>
.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.box-card {
  margin: 0;
  padding: 12px;
  border-radius: 8px;
  box-shadow: var(--shadow);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
  padding: 10px 12px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-table {
  flex: 1;
  overflow: auto;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 10px 12px;
  background-color: var(--card-bg);
}

.image-uploader,
.sku-image-uploader {
  text-align: center;

  .el-image {
    border: 1px solid var(--border-color);
    transition: var(--transition);
    &:hover {
      border-color: var(--primary-color);
    }
  }

  .el-upload__tip {
    margin-top: 8px;
    color: var(--text-secondary);
    font-size: 12px;
  }
}
</style>